using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.User;
using B.S.NewMedical.Domain.User;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.NewMedical.Api.Write.Application.Handler.User
{
    /// <summary>
    /// 获取权限树处理器
    /// </summary>
    public class GetPermissionTreeHandler : IRequestHandler<GetPermissionTreeCommand, ApiResult<List<PermissionTreeDto>>>
    {
        private readonly IBaseRepository<PermissionModel> _permissionRepository;
        private readonly IBaseRepository<UserPermissionModel> _userPermissionRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetPermissionTreeHandler> _logger;

        public GetPermissionTreeHandler(
            IBaseRepository<PermissionModel> permissionRepository,
            IBaseRepository<UserPermissionModel> userPermissionRepository,
            IMapper mapper,
            ILogger<GetPermissionTreeHandler> logger)
        {
            _permissionRepository = permissionRepository;
            _userPermissionRepository = userPermissionRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult<List<PermissionTreeDto>>> Handle(GetPermissionTreeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有权限
                var allPermissions = _permissionRepository.GetAll()
                    .Where(p => !p.IsDeleted && p.IsEnabled)
                    .OrderBy(p => p.SortOrder)
                    .ToList();

                // 获取用户权限（如果指定了用户ID）
                var userPermissions = new List<UserPermissionModel>();
                if (request.UserId.HasValue)
                {
                    userPermissions = _userPermissionRepository.GetAll()
                        .Where(up => up.UserId == request.UserId.Value && !up.IsDeleted && up.IsEnabled)
                        .ToList();
                }

                // 按模块分组
                var permissionGroups = allPermissions
                    .GroupBy(p => p.Module)
                    .Select(g => new PermissionTreeDto
                    {
                        ModuleName = GetModuleDisplayName(g.Key),
                        ModuleCode = g.Key,
                        IsChecked = false, // 模块级别的选中状态需要根据子权限计算
                        Permissions = g.Select(p => new PermissionItemDto
                        {
                            PermissionId = p.Id,
                            PermissionName = p.PermissionName,
                            PermissionCode = p.PermissionCode,
                            IsChecked = userPermissions.Any(up => up.PermissionId == p.Id)
                        }).ToList()
                    })
                    .ToList();

                // 计算模块级别的选中状态
                foreach (var group in permissionGroups)
                {
                    var checkedPermissions = group.Permissions.Count(p => p.IsChecked);
                    var totalPermissions = group.Permissions.Count;
                    group.IsChecked = checkedPermissions > 0 && checkedPermissions == totalPermissions;
                }

                _logger.LogInformation("成功获取权限树，共{Count}个模块", permissionGroups.Count);

                return new ApiResult<List<PermissionTreeDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取权限树成功",
                    Data = permissionGroups
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取权限树时发生异常");
                return new ApiResult<List<PermissionTreeDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取权限树失败：" + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取模块显示名称
        /// </summary>
        private string GetModuleDisplayName(string moduleCode)
        {
            return moduleCode switch
            {
                "OutpatientDoctor" => "门诊医生",
                "SystemManagement" => "系统管理",
                "OutpatientManagement" => "门诊管理",
                "FinancialManagement" => "财务管理",
                "PharmacyManagement" => "药房管理",
                "InpatientManagement" => "住院管理",
                "OutpatientBilling" => "门诊收费",
                "DrugstoreManagement" => "药库管理",
                _ => moduleCode
            };
        }
    }
} 